'use strict';
import { Controller } from 'egg';
const fs = require('fs');

export default class GoodsController extends Controller {
  public async addSwiper() {
    const { ctx } = this;
    const fileName = Date.now() + ctx.helper.random();
    const time = ctx.helper.getNowFormatDate();
    const path = 'app/public/uploads/' + time + '/' + fileName
    const store = 'public/uploads/' + time + '/' + fileName;
    const checkDir = fs.existsSync('app/public/uploads/' + time + '/'); // 判断目录是否存在
    if (!checkDir) {
        fs.mkdirSync('app/public/uploads/' + time + '/', { recursive: true }, (err) => { console.log(err); }) // 不存在则创建目录
    }
    let file = ctx.request.files[0];
    let files = fs.readFileSync(file.filepath);
    fs.writeFileSync(path, files)
    try {
      let res = await ctx.service.swiper.addSwiper(store);
      ctx.success(res, '发布成功');
    } catch (e) {
      console.log(e);
      ctx.error(423, ctx.helper.errorCode[423]);
    }
  }
  public async getSwiper() {
    const { ctx } = this;
    try {
      let res = await ctx.service.swiper.getSwiper();
      ctx.success(res, '查询成功');
    } catch (e) {
      console.log(e);
      ctx.error(423, ctx.helper.errorCode[423]);
    }
  }
}